package com.neusoft.tmall.ums.controller;

import com.neusoft.tmall.ums.entity.UmsAdmin;
import com.neusoft.tmall.ums.entity.UmsAdminExample;
import com.neusoft.tmall.ums.service.UmsAdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("admin")
public class UmsAdminController {
    private static final Logger logger = LoggerFactory.getLogger(UmsAdminController.class);

    @Autowired
    private UmsAdminService umsAdminService;
//    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("hello")
    public String hello() {
        return "hello, Security";
    }

    @GetMapping("welcome")
    public String welcome() {
        return "hello, welcome";
    }

    @PostMapping("login")
    public Object login(String username, String password) {
//        System.out.println("username:" + username + ", password:" + password);
        logger.info("username:{}, password:{}", username, password);
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria()
                .andUsernameEqualTo(username);
        List<UmsAdmin> umsAdmins = umsAdminService.selectByExample(example);
        if (umsAdmins == null || umsAdmins.size() == 0) {
            return "账号或密码错误";
        }

        UmsAdmin umsAdmin = umsAdmins.get(0);
        logger.info("umsAdmin:{}", umsAdmin);
        if (!passwordEncoder.matches(password, umsAdmin.getPassword())) {
            return "账号或密码错误";
        }

        return "登录成功";
    }
}
